#! /bin/bash

DISK=/dev/sda
PART_EFI=/dev/sda1
PART_SWAP=/dev/sda2
PART_ROOT=/dev/sda3

show () {
    echo -e "\e[36;1m$*\e[0m"
}

trytodo () {
    show "$1"
    $2
    if [ $? -ne 0 ]
    then
        show "[ failed ]"
        exit 1
    fi
}

ensure () {
    if [ $1 != y ]
    then
        show "user denied"
        exit 1
    fi
}

make_part () {
    parted $DISK mklabel gpt
    parted $DISK mkpart primary fat32 -- 0% 512MB
    parted $DISK mkpart primary ext4  -- 512MB 2GB
    parted $DISK mkpart primary ext4  -- 2GB 100%
}

format_part () {
    mkfs.vfat $PART_EFI
    mkswap $PART_SWAP
    swapon $PART_SWAP
    mkfs.ext4 $PART_ROOT
}

mount_part () {
    mount $PART_ROOT /mnt
    mkdir -p /mnt/boot/
    mount $PART_EFI /mnt/boot/
}

###########################################################################

show "Arch Linux 2020.10.1 Setup"
show "make sure your network ok[y/n]"
read -p "=> " ANS
ensure $ANS


timedatectl set-ntp true

trytodo "make part"     "make_part"

trytodo "format part"   "format_part"

trytodo "mount part"    "mount_part"

trytodo "base packages" "pacstrap /mnt base linux linux-firmware"

trytodo "genfstab"      "genfstab -U /mnt > /mnt/etc/fstab"

cp ./setup-chroot.sh /mnt
cp ./edit-sudoers.sh /mnt
sync
trytodo "arch chroot"   "arch-chroot /mnt /setup-chroot.sh"
rm /mnt/setup-chroot.sh
rm /mnt/edit-sudoers.sh
sync


show "you can reboot now!"

show "[ finish ]"

